<template>
  <el-card>
    <el-button type="primary" icon="Plus" @click="addTrademark" v-has="'btn.Trademark.add'">
      添加品牌
    </el-button>
    <el-table :data="trademarkData" style="margin: 10px 0" border>
      <el-table-column type="index" label="序号" width="80px" align="center"></el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width" align="center"></el-table-column>
      <el-table-column label="品牌LOGO" width="width" align="center">
        <template #="{ row }">
          <img :src="row.logoUrl" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width" align="center">
        <template #="{ row }">
          <el-button type="primary" size="small" icon="Edit" @click="updateTrademark(row)"></el-button>
          <el-popconfirm icon="Delete" :title="`您确实要删除${row.tmName}吗？`" width="250px"
            @confirm="removeTrademark(row.id)">
            <template #reference>
              <el-button type="danger" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="width: 100%" v-model:current-page="currentPage" v-model:page-size="pageSize"
      :page-sizes="[3, 5, 7, 9]" :background="true" layout="prev, pager, next, jumper, ->, sizes, total" :total="total"
      @current-change="getReqHasTrademark" @size-change="changeSizePage" />
  </el-card>

  <el-dialog :title="title" v-model="dialogVisible" width="50%">
    <el-form style="width: 80%" :model="trademarkParms" :rules="rules" ref="trademarkForm" label-width="80px">
      <el-form-item label="品牌名称" prop="tmName">
        <el-input v-model="trademarkParms.tmName" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="trademarkParms.logoUrl" :src="trademarkParms.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick } from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import type {
  Records,
  TrademarkResponseData,
  Trademark,
} from '@/api/product/trademark/types'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'

let currentPage = ref(1)
let pageSize = ref(3)
let total = ref(0)
let dialogVisible = ref(false)
let title = ref('')
let trademarkForm = ref()
let trademarkData = reactive<Records>([])
let trademarkParms = reactive<Trademark>({
  tmName: '',
  logoUrl: '',
})

onMounted(() => {
  getReqHasTrademark()
})

const getReqHasTrademark = async (pager = 1) => {
  currentPage.value = pager
  let res: TrademarkResponseData = await reqHasTrademark(
    currentPage.value,
    pageSize.value,
  )
  if (res.code === 200) {
    trademarkData = res.data.records
    total.value = res.data.total
  }
}

const changeSizePage = () => {
  getReqHasTrademark()
}

const addTrademark = () => {
  title.value = '添加品牌'
  trademarkParms.id = 0
  trademarkParms.tmName = ''
  trademarkParms.logoUrl = ''
  dialogVisible.value = true
  nextTick(() => {
    trademarkForm.value.clearValidate('tmName')
    trademarkForm.value.clearValidate('logoUrl')
  })
}

const updateTrademark = (row: Trademark) => {
  title.value = '修改品牌'
  Object.assign(trademarkParms, row)
  dialogVisible.value = true
  nextTick(() => {
    trademarkForm.value.clearValidate('tmName')
    trademarkForm.value.clearValidate('logoUrl')
  })
}

const confirm = async () => {
  await trademarkForm.value.validate()
  let res = await reqAddOrUpdateTrademark(trademarkParms)
  if (res.code === 200) {
    getReqHasTrademark(trademarkParms.id ? currentPage.value : 1)
    ElMessage.success(trademarkParms.id ? '修改成功' : '添加成功')
  } else {
    ElMessage.error(trademarkParms.id ? '修改失败' : '添加失败')
  }
  dialogVisible.value = false
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('上传格式务必是jpg/png/gif格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
  return true
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  trademarkParms.logoUrl = response.data
  trademarkForm.value.clearValidate('logoUrl')
}
const validatorTmName = (rule: any, value: string, callback: any) => {
  console.log(rule, 'rule');

  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称不能小于2位'))
  }
}

const validatorLogoUrl = (rule: any, value: string, callback: any) => {
  console.log(rule, 'rule');
  if (value) {
    callback()
  } else {
    callback(new Error('LOGO不能为空'))
  }
}

const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
}

const removeTrademark = async (id: number) => {
  let res = await reqDeleteTrademark(id)
  if (res.code === 200) {
    ElMessage.success('删除品牌成功')
    getReqHasTrademark(
      trademarkData.length > 1 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage.error('删除品牌失败')
  }
}
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
